package com.ruoyi.foodworks.controller;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.foodworks.domain.Comments;
import com.ruoyi.foodworks.service.CommentsService;
import com.ruoyi.foodworks.service.WorksService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * 作品评论Controller
 * 
 * @author lpt 
 * @date 2025-08-12
 */
@RestController
@Controller("foodWorksCommentsController")
@RequestMapping("/foodworks/comments")
public class CommentsController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(CommentsController.class);
    
    @Autowired
    private CommentsService commentsService;
    
    @Autowired
    private WorksService worksService;

    /**
     * 获取用户加入时间统计（用于dashboard图表）
     */
    @GetMapping("/userJoinStats")
    public AjaxResult getUserJoinStats() {
        try {
            // 调用专门的统计方法
            List<Map<String, Object>> stats = commentsService.getUserJoinStats();
            log.info("用户加入统计结果: {}", stats);
            return AjaxResult.success(stats);
        } catch (Exception e) {
            log.error("获取用户加入统计失败", e);
            return AjaxResult.error("获取用户加入统计失败");
        }
    }

    /**
     * 获取评论数量统计（用于dashboard图表）
     */
    @GetMapping("/commentStats")
    public AjaxResult getCommentStats() {
        try {
            // 调用专门的统计方法
            List<Map<String, Object>> stats = commentsService.getCommentStats();
            log.info("评论统计结果: {}", stats);
            return AjaxResult.success(stats);
        } catch (Exception e) {
            log.error("获取评论统计失败", e);
            return AjaxResult.error("获取评论统计失败");
        }
    }

    /**
     * 获取评论总数（用于dashboard统计）
     */
    @GetMapping("/count")
    public AjaxResult getCommentsCount() {
        try {
            Comments comments = new Comments();
            // 只统计未删除的评论
            comments.setDel(0);
            List<Comments> list = commentsService.selectCommentsList(comments);
            return AjaxResult.success(list.size());
        } catch (Exception e) {
            log.error("获取评论总数失败", e);
            return AjaxResult.error("获取评论总数失败");
        }
    }

    @GetMapping("/target")
    public AjaxResult getCommentsByTarget(@RequestParam Integer targetId) {
        List<Comments> list = commentsService.selectCommentsWithUserAndLikes(targetId);
        return AjaxResult.success(list);
    }

    /**
     * 查询作品评论列表
     */
    @PreAuthorize("@ss.hasPermi('foodworks:comments:list')")
    @GetMapping("/list")
    public TableDataInfo list(Comments comments)
    {
        startPage();
        List<Comments> list = commentsService.selectCommentsList(comments);
        return getDataTable(list);
    }

    /**
     * 导出作品评论列表
     */
    @PreAuthorize("@ss.hasPermi('foodworks:comments:export')")
    @Log(title = "作品评论", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Comments comments)
    {
        List<Comments> list = commentsService.selectCommentsList(comments);
        ExcelUtil<Comments> util = new ExcelUtil<Comments>(Comments.class);
        util.exportExcel(response, list, "作品评论数据");
    }

    /**
     * 获取作品评论详细信息
     */
    @PreAuthorize("@ss.hasPermi('foodworks:comments:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(commentsService.selectCommentsById(id));
    }

    /**
     * 新增作品评论
     */
    @PreAuthorize("@ss.hasPermi('foodworks:comments:add')")
    @Log(title = "作品评论", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Comments comments)
    {
        try {
            // 1. 保存评论
            int result = commentsService.insertComments(comments);
            
            if (result > 0) {
                // 2. 处理积分流水（异步处理，避免影响评论响应速度）
                CompletableFuture.runAsync(() -> {
                    try {
                        processCommentPointFlow(comments.getUserId().longValue());
                    } catch (Exception e) {
                        log.error("处理评论积分失败", e);
                    }
                });
                
                return AjaxResult.success("评论成功");
            } else {
                return AjaxResult.error("评论失败");
            }
        } catch (Exception e) {
            log.error("添加评论异常", e);
            return AjaxResult.error("评论失败");
        }
    }

    /**
     * 修改作品评论
     */
    @PreAuthorize("@ss.hasPermi('foodworks:comments:edit')")
    @Log(title = "作品评论", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Comments comments)
    {
        return toAjax(commentsService.updateComments(comments));
    }

    /**
     * 删除作品评论
     */
    @PreAuthorize("@ss.hasPermi('foodworks:comments:remove')")
    @Log(title = "作品评论", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(commentsService.deleteCommentsByIds(ids));
    }

    /**
     * 审核作品评论
     */
    @PreAuthorize("@ss.hasPermi('foodworks:comments:audit')")
    @Log(title = "评论审核", businessType = BusinessType.UPDATE)
    @PutMapping("/audit")
    public AjaxResult audit(@RequestBody Map<String, Object> auditData)
    {
        Integer commentId = (Integer) auditData.get("commentId");
        Integer status = (Integer) auditData.get("status");
        String remark = (String) auditData.get("remark");
        
        Comments comments = new Comments();
        comments.setId(commentId);
        comments.setStatus(status);
        
        return toAjax(commentsService.updateComments(comments));
    }

    /**
     * 批量审核作品评论
     */
    @PreAuthorize("@ss.hasPermi('foodworks:comments:audit')")
    @Log(title = "批量评论审核", businessType = BusinessType.UPDATE)
    @PutMapping("/batchAudit")
    public AjaxResult batchAudit(@RequestBody Map<String, Object> auditData)
    {
        List<Integer> commentIds = (List<Integer>) auditData.get("commentIds");
        Integer status = (Integer) auditData.get("status");
        String remark = (String) auditData.get("remark");
        
        int result = 0;
        for (Integer commentId : commentIds) {
            Comments comments = new Comments();
            comments.setId(commentId);
            comments.setStatus(status);
            
            result += commentsService.updateComments(comments);
        }
        
        return toAjax(result);
    }

    /**
     * 处理评论积分流水
     */
    private void processCommentPointFlow(Long userId) {
        try {
            // 调用积分服务处理积分流水
            Map<String, Object> pointResult = worksService.processInteractionCommentPoint(userId);
            
            if ((Boolean) pointResult.get("success")) {
                log.info("用户{}评论积分处理成功，获得积分：{}", userId, pointResult.get("pointChange"));
            } else {
                log.error("用户{}评论积分处理失败：{}", userId, pointResult.get("message"));
            }
        } catch (Exception e) {
            log.error("处理评论积分异常", e);
        }
    }

    /**
     * 测试积分规则查询
     */
    @GetMapping("/test-point-rules")
    public AjaxResult testPointRules() {
        try {
            List<Map<String, Object>> allRules = worksService.selectAllValidPointRules();
            Map<String, Object> commentRule = worksService.selectInteractionCommentRule();
            
            Map<String, Object> result = new HashMap<>();
            result.put("allRules", allRules);
            result.put("commentRule", commentRule);
            
            return AjaxResult.success("查询成功", result);
        } catch (Exception e) {
            log.error("测试积分规则查询失败", e);
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }
}
